package com.an.httptest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

public class Server {

	public static int PORT = 6665;

	public static void main(String[] args) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(boss, worker) // 设置两个EventLoop
				.channel(NioServerSocketChannel.class) // 设置一个服务器端的通道实现
				.option(ChannelOption.SO_BACKLOG, 128) // 用来给ServerChannel添加配置
				.childOption(ChannelOption.SO_KEEPALIVE, true) // 用来给接收到的通道添加配置

				// 此方法用来设置业务处理类（自定义的handler）
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {

						// 向管道加入处理器
						// 加入一个Netty提供的 HTTP Server codec => [coder - decoder]
						ch.pipeline().addLast("httpcodex", new HttpServerCodec());

						// 自定义处理器
						ch.pipeline().addLast(new MyHandler());
					}
				});

		try {

			bind(serverBootstrap, PORT);
			

		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}

	}

	private static void bind(final ServerBootstrap serverBootstrap, final int port) {
		ChannelFuture channelFuture = serverBootstrap.bind(port)
				.addListener(new GenericFutureListener<Future<? super Void>>() {
					public void operationComplete(Future<? super Void> future) {
						if (future.isSuccess()) {
							System.out.println("端口[" + port + "]绑定成功!");
							// 注册关闭监听。若不注册，则程序直接走完。。。结束
							// future.channel().closeFuture().sync();
						} else {
							System.err.println("端口[" + port + "]绑定失败!");
							bind(serverBootstrap, port + 1);
						}
					}
				});
		try {
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
